package sicnu.cs.ich.ich.service.impl;

import com.google.common.annotations.Beta;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import sicnu.cs.ich.ich.mapper.IchMapper;
import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/12/7-22:36
 **/
@Service
public class BloomFilterService {

    @Autowired
    private IchMapper ichMapper;

    private BloomFilter<Integer> bf;

    /**
     * 程序启动时候加载此方法
     */
    @PostConstruct
    public void initBloomFilter() {
        List<Integer> ichIds = ichMapper.selectAllId();
        if (CollectionUtils.isEmpty(ichIds)) {
            return;
        }
        // 创建布隆过滤器（默认误差3%）
        bf = BloomFilter.create(Funnels.integerFunnel(), ichIds.size());
        // 将数据库中所有用户id压入布隆过滤器，存于JVM内存
        for (Integer ichId : ichIds) {
            bf.put(ichId);
        }
    }

    /**
     * 判断非遗id是否存在于布隆过滤器
     */
    public boolean ichIdExist(Integer ichId) {
        return bf.mightContain(ichId);
    }
}